/**
 * date：2010-11-25
 * author：eason
 * description：树状组件。
 * 
 */
package com.pickgliss.ui.controls.tree
{
	import com.pickgliss.events.TreeEvent;
	import com.pickgliss.ui.controls.ScrollPanel;
	import com.pickgliss.ui.core.Component;
	
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	[Event(name="itemSelected",type="com.pickgliss.events.TreeEvent")]
	
	public class Tree extends Component
	{
		protected var _items : Vector.<TreeItem>;
		
		protected var _topItems : Vector.<TreeItem>;
			
		private var _layoutRect : Rectangle;
		
		private var _treeH : Number;
		
		public function Tree(items : Vector.<TreeItem> = null)
		{
			super();
			
			_topItems = new Vector.<TreeItem>();
			
			setItems(items);
		}
		public function setItems(items : Vector.<TreeItem>):void
		{
			_items = items;
			if(_items){
				initTree();
			}
		}
		/**
		 * 初始化组件。 
		 * 
		 */		
		protected function initTree():void
		{
			var item : TreeItem;
			for(var i : int = 0; i < _items.length; i++){
				item = _items[i] as TreeItem;
				if(item.depth == 0){
					_topItems.push(item);
					addChild(item.getView());
					
					item.addEventListener(TreeEvent.LIST_CHANGED, onItemChanged);
					item.addEventListener(TreeEvent.ITEM_OPEN, onItemChanged);
					item.addEventListener(TreeEvent.ITEM_CLOSE, onItemChanged);
					
					item.addEventListener(TreeEvent.ITEM_SELECTED, onItemSelected);
				}
			}
			refreshTree();
		}
		
		/**
		 * 当项目发生改变时(如展开/关闭/改变)的处理函数. 
		 * @param event
		 * 
		 */		
		private function onItemChanged(event:TreeEvent):void
		{
			refreshTree();
		}
			
		private function onItemSelected(event:TreeEvent):void
		{
			this.dispatchEvent(event);
		}

		/**
		 * 刷新树状视图. 
		 * 
		 */		
		private function refreshTree():void
		{
			var item : TreeItem;
			
			_treeH = _topItems[0].getHeight();
			
			for(var i : int = 1; i < _topItems.length; i++){
				item = _topItems[i] as TreeItem;
				_treeH += item.getHeight();
				item.getView().y = _topItems[i - 1].getView().y + _topItems[i - 1].getHeight();
			}
		}
		override public function get height():Number
		{
			return _treeH;
		}
		
		private function removeAllItems():void
		{
			var item : TreeItem;
			for(var i : int = 0; i < _topItems.length; i++){
				item = _topItems[i] as TreeItem;
				removeChild(item.getView());
				
				item.removeEventListener(TreeEvent.LIST_CHANGED, onItemChanged);
				item.removeEventListener(TreeEvent.ITEM_OPEN, onItemChanged);
				item.removeEventListener(TreeEvent.ITEM_CLOSE, onItemChanged);
				
				item.removeEventListener(TreeEvent.ITEM_SELECTED, onItemSelected);
				
				item.dispose();
				item = null;
			}
			_topItems = null;
		}

		override public function dispose():void
		{
			removeAllItems();
			super.dispose();
		}
	}
}